package com.itools.core.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xuchang
 */
@Component
public class CustomClientAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Autowired
    private ObjectMapper objectMapper;
 
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        Map<String, Object> map = new HashMap();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("message", "client_id或client_secret错误");
        map.put("success", false);
        map.put("data", null);
        response.setHeader("Content-Type", "application/json;charset=utf-8");
 
        response.getWriter().print(objectMapper.writeValueAsString(map));
        response.getWriter().flush();
    }
}